/*
Copyright (c) 2009, Dan Hagerstrand and contributors
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of Cirrus Creative nor the names of its
  contributors may be used to endorse or promote products derived from this
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <allegro.h>

#include "../../include/beng/BengInterface.h"
#include "../../include/beng/System.h"

BengIGfx::~BengIGfx(void)
{
    this->deinit();
}

void BengIGfx::init(void)
{
    BengSystem *system = this->interface->system;
    system->consprint("\n\nInitializing video!");

    // TODO: Replace with configuration loading
    this->displayW = this->interface->system->windowW;
    this->displayH = this->interface->system->windowH;
    this->displayD = 32;
    this->isFullScreen = false;
    this->fullScreenDriver = GFX_AUTODETECT_FULLSCREEN;
    this->windowDriver = GFX_AUTODETECT_WINDOWED;
    this->isNotClipped = false;

    system->consprintf("\nTrying mode: %ix%ix%i...", this->displayW, this->displayH, this->displayD);

    set_color_depth(this->displayD);

    if (set_gfx_mode(this->windowDriver, this->displayW, this->displayH, 0, 0) != 0)
        system->giveError(BENG_ERROR_FATAL, "Could not open video device!\n%s", allegro_error);

    textprintf_centre_ex(screen, font, SCREEN_W/2, SCREEN_H-40, makecol(255, 255, 255), -1,
    "BlitzzEngine %s", BENG_VERSION_STRING);
    textprintf_centre_ex(screen, font, SCREEN_W/2, SCREEN_H-24, makecol(255, 255, 255), -1,
     "%s", this->interface->system->gameName.string);

    system->consprint("\nSuccess!\n\nSetting switch mode...");

    this->interface->guiMode = BENG_INTERFACE_LOADED_VIDEO;

    if (set_display_switch_mode(SWITCH_BACKGROUND) != 0 && set_display_switch_mode(SWITCH_BACKAMNESIA) != 0)
        system->consprint("\nFailed. Continuing anyway.");

    system->consprint("\nCreating buffer bitmaps...");
    this->drawBufferMemory = create_bitmap(SCREEN_W, SCREEN_H);
    if (!this->drawBufferMemory)
        system->giveError(BENG_ERROR_FATAL, "Could not create buffer bitmap!\n%s", allegro_error);
    this->drawTarget = this->drawBufferMemory;

    this->isInit = true;
}

void BengIGfx::deinit(void)
{
    BengSystem *system = this->interface->system;

    if (!this->isInit) // Was already deinited, so ignore.
        return;

    system->consprint("\n\nDeinitializing graphics...");

    system->consprint("\n\nDestroying buffer bitmaps...");

    this->drawTarget = NULL;
    if (this->drawBufferMemory)
        destroy_bitmap(this->drawBufferMemory);

    system->consprint("\n\nClosing video device...");

    set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);

    this->interface->guiMode = BENG_INTERFACE_LOADED_TEXT;

    this->isInit = false;

    system->consprint("\nDone!");
}

void BengIGfx::drawLoop(void)
{
    BengScene *scene;
    BengCamera *camera;

    scene = this->interface->system->scene;

    //clear_to_color(this->drawTarget_, makecol(0,0,0));

    camera = scene->iterateCamera();

    while (camera)
    {
        drawScene(scene, camera);

        camera = scene->iterateCamera();
    }


    // Silly debug info. May replace with less intrusive system layer.

    /*textprintf_ex(this->drawTarget_, font, 0, 0, makecol(255, 255, 255), makecol(0, 0, 0),
        "Timer: %i", this->interface_->tics_);

    textprintf_ex(this->drawTarget_, font, 0, 8, makecol(255, 255, 255), makecol(0, 0, 0),
        "Objs:");

    for (int l = 0; l < numlayers; l++)
    {
        layer = this->interface_->system_->scene->getLayer(l);

        textprintf_ex(this->drawTarget_, font, 48 + (l*32), 8, makecol(255, 255, 255), makecol(0, 0, 0),
            "%i", layer->getNumObjects());
    }*/

    if (this->tooSlow > 0)
    {
        textout_ex(this->drawTarget, font, "!SLOW!", this->drawTarget->w - text_length(font, "!SLOW!"), 0,
            makecol(255, 255, 255), makecol(128, 0, 0));
        this->tooSlow--;
    }

    this->updateScreen();
}

void BengIGfx::drawScene(BengScene *scene, BengCamera *camera)
{
    BengLayer *layer;
    BengObject *object;
    short int **map;
    int numlayers = this->interface->system->scene->getNumLayers();
    int viewoffsetx, viewoffsety, viewwidth, viewheight;

    camera->getRegion(viewoffsetx, viewoffsety, viewwidth, viewheight);

    set_clip_rect(this->drawTarget, viewoffsetx, viewoffsety, viewoffsetx + viewwidth - 1, viewoffsety + viewheight - 1);

    for (int l = 0; l < numlayers; l++)
    {
        BengVector camvector;
        int camx, camy;
        int startx = 0;
        int starty = 0;
        int tempsizex, tempsizey;
        int layersizex, layersizey, tilesizex, tilesizey;

        layer = scene->getLayer(l);

        if (!layer->getVisibility())
            continue;

        camera->getPos(camvector);

        camx = (camvector.x.intValue/65536) - viewoffsetx;
        camy = (camvector.y.intValue/65536) - viewoffsety;

        layer->getSize((unsigned int&)layersizex, (unsigned int&)layersizey);
        layer->getTileSize((unsigned int&)tilesizex, (unsigned int&)tilesizey);

        startx = (camx / tilesizex);
        if (startx < 0)
            startx = 0;
        starty = (camy / tilesizey);
        if (starty < 0)
            starty = 0;

        tempsizex = (camx / tilesizex) + (drawTarget->w / tilesizex) + 1;
        if (tempsizex < startx)
            tempsizex = startx;
        tempsizey = (camy / tilesizey) + (drawTarget->h / tilesizey) + 1;
        if (tempsizey < starty)
            tempsizey = starty;

        if (layersizex > tempsizex)
            layersizex = tempsizex;
        if (layersizey > tempsizey)
            layersizey = tempsizey;

        map = layer->getRawData();

        for (int i = starty; i < layersizey; i++)
        {
            for (int j = startx; j < layersizex; j++)
            {
                BengResource<BengISprite> *tileset = layer->getTileset();

                if (map[i][j] == 0)
                    continue;

                if (!tileset || tileset->getData(map[i][j] - 1) == NULL)
                {
                    rect(this->drawTarget, (j*tilesizex) - camx, (i*tilesizey) - camy,
                        ((j+1)*tilesizex) - camx - 1, ((i+1)*tilesizey) - camy - 1, makecol(255, 0, 0));
                    textprintf_ex(this->drawTarget, font, (j*tilesizex) - camx, (i*tilesizey) - camy, makecol(255, 255, 255), makecol(255, 0, 0),
                        "%i", map[i][j]);
                }
                else
                {
                    BengISprite *sprite = tileset->getData(map[i][j] - 1);
                    draw_sprite(this->drawTarget, sprite->data, (j*tilesizex) - camx, (i*tilesizey) - camy);
                }
            }
        }

        for (layer->objectIterator = layer->objectList.begin();
        layer->objectIterator != layer->objectList.end(); ++layer->objectIterator)
        {
            object = *layer->objectIterator;

            if (object && !object->internFlags_[BENG_OBJECT_INTERN_FOR_DELETION] )
            {
                BengISprite *sprite = object->getSprite();
                int x = ((object->pos.x.intValue)/BENG_UNIT) - camx;
                int y = ((object->pos.y.intValue)/BENG_UNIT) - camy;

                if (sprite == NULL)
                {
                    ellipse(this->drawTarget, x, y,
                    (object->size.x.intValue)/BENG_UNIT/2, (object->size.y.intValue)/BENG_UNIT/2, makecol(255, 100, 0));
                }
                else
                {
                    draw_sprite(this->drawTarget, sprite->data, x - (sprite->width/2), y - (sprite->height/2));
                }

                object->onDraw(this->drawTarget);
                if (this->isNotClipped)
                    set_clip_rect(this->drawTarget, viewoffsetx, viewoffsety, viewoffsetx + viewwidth - 1, viewoffsety + viewheight - 1);
            }
        }
    }

    set_clip_rect(this->drawTarget, 0, 0, this->drawTarget->w - 1, this->drawTarget->h - 1);
}

void BengIGfx::disableRegionClipping(void)
{
    set_clip_rect(this->drawTarget, 0, 0, this->drawTarget->w - 1, this->drawTarget->h - 1);
    this->isNotClipped = true;
}

void BengIGfx::updateScreen(void)
{
    //vsync();

    blit(this->drawBufferMemory, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H);
}
